package com.md5;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.lang.Character.UnicodeBlock;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.URL;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.sql.Clob;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletResponse;

import com.connectDB.DBPool;

/**
 * 顾巍的工具类
 * 
 * @author Administrator
 * 
 */
public class GuWeiUtil {
	/**
	 * 得到本机的ip地址
	 * 
	 * @return
	 */

	public static String getDateBackBaseOnCurrent(int backInterval) {
		SimpleDateFormat dft = new SimpleDateFormat("yyyyMMdd");
		String dateString = null;
		Date beginDate = new Date();
		Calendar date = Calendar.getInstance();
		date.setTime(beginDate);
		date.set(Calendar.DATE, date.get(Calendar.DATE) - backInterval);
		dateString = dft.format(date.getTime());
		return dateString;
	}

	public static String gethostIPaddress() {
		InetAddress addr;
		String ipaddress = null;
		try {
			addr = InetAddress.getLocalHost();
			ipaddress = addr.getHostAddress();
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return ipaddress;
	}
	/**
	 * 等分list
	 * @param all
	 * @param dividedList
	 * @param partsize 分组的个数
	 */
	public void divideList(List<Map<String, String>> all,
			List<Object> dividedList, int partsize) {
		int allsize = all.size();
		int remainder = allsize % partsize;
		int average = (allsize - remainder) / partsize;
		for (int i = 0; i < partsize - 1; i++) {
			List<Map<String, String>> subList = new ArrayList<Map<String, String>>();
			for (int j = average * i; j < average * (i + 1); j++) {
				subList.add(all.get(j));
			}
			dividedList.add(subList);
		}
		List<Map<String, String>> lastsubList = new ArrayList<Map<String, String>>();
		for (int k = average * (partsize - 1); k < allsize; k++) {
			lastsubList.add(all.get(k));
		}
		dividedList.add(lastsubList);
	}
	/**
	 * 文件拷贝实现方法
	 * 
	 * @param f1
	 * @param f2
	 * @throws Exception
	 */
	public static void forChannel(File f1, File f2) throws Exception {
		int length = 2097152;
		FileInputStream in = new FileInputStream(f1);
		FileOutputStream out = new FileOutputStream(f2);
		FileChannel inC = in.getChannel();
		FileChannel outC = out.getChannel();
		ByteBuffer b = null;
		try {
			while (true) {
				if (inC.position() == inC.size()) {
					break;
				}
				if ((inC.size() - inC.position()) < length) {
					length = (int) (inC.size() - inC.position());
				} else
					length = 2097152;
				b = ByteBuffer.allocateDirect(length);
				inC.read(b);
				b.flip();
				outC.write(b);
				outC.force(false);
			}
		} finally {
			inC.close();
			outC.close();
			in.close();
			out.close();
		}
	}

	/**
	 * 得到properties的配置文件
	 * 
	 * @return
	 */
//	public String getproperties() {
//
//		Properties props = new Properties();
//
//		InputStream in = ReadPro.class.getClassLoader().getResourceAsStream(
//				"orclbean.properties");
//		try {
//			props.load(in);
//			in.close();
//		} catch (IOException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
//
//		in = null;
//		String username = props.getProperty("username");
//		return username;
//	}

	/**
	 * 用累加的方法计算文件夹下记录数
	 * 
	 * @param filePath
	 * @return
	 */
	public int leijiashuliang(String filePath) {

		// filePath="D:/160W处理后的数据/444/1";
		java.io.File file = new java.io.File(filePath);
		String[] allpath = file.list();
		int shuliang = 0;
		try {
			for (String myfile : allpath) {
				FileReader read = new FileReader(filePath + "/" + myfile); // 其中一个文件
				BufferedReader br = new BufferedReader(read);

				String row;
				while ((row = br.readLine()) != null) {
					if (!row.equals("")) {
						shuliang = shuliang + 1;
					}
				}
				// 写入错误的
				br.close(); // 关闭读取流
				//					
			}
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return shuliang;

	}

	/**
	 * txt文本导入到数据库
	 */
	public void daoru(String filePath) {
		// String filePath="D:/4000W查询出来的数据/20130701_data/data";
		java.io.File file = new java.io.File(filePath);
		String[] allpath = file.list();
		Connection con = DBPool.getInstance().getConnection();
		PreparedStatement ps = null;
		String sql = "insert into accp_20130702(BATCH_ID,BUSI_DATE,DIR_NO,NODE_ID,ON_LINE,S_VERSION,UPLOAD_TIME)values(?,?,?,?,?,?,?)";
		try {
			ps = con.prepareStatement(sql);
			for (String myfile : allpath) {
				System.out.println(filePath + "/" + myfile);
				FileReader read = new FileReader(filePath + "/" + myfile); // 其中一个文件
				BufferedReader br = new BufferedReader(read);
				String row;
				while ((row = br.readLine()) != null) {
					ArrayList<String> wulist = new ArrayList<String>(); // 没有文件的数据wulist
					if (!row.equals("")) {
						String[] myrow = row.split(",");
						// 加入数据库
						// insert into
						// accp_20130702(BATCH_ID,BUSI_DATE,DIR_NO,NODE_ID,ON_LINE,S_VERSION,UPLOAD_TIME)values('1111111','20130702',3,'1',4,1,'222222')
						ps.setString(1, myrow[0]);
						ps.setString(2, "20130702");
						ps.setInt(3, 3);
						ps.setString(4, "1");
						ps.setInt(5, 4);
						ps.setInt(6, 1);
						ps.setString(7, "20130702150059");
						ps.execute();
					}
				}
				br.close(); // 关闭读取流
			}
			con.close();
			// 写入错误的
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				if (null != ps) {
					ps.close();
				}
			} catch (Exception e) {
			}
		}
	}

	/**
	 * 判断字符串是否为NULL或者为空
	 * 
	 * @param value
	 * @return
	 */
	public static boolean isNotEmpty(String value) {
		boolean result = false;
		if (value != null) {
			if (value.trim().length() > 0) {
				result = true;
			}
		}
		return result;
	}

	/**
	 * 判断一个对象是否为null
	 * 
	 * @param value
	 * @return
	 */
	public static boolean isNotNull(Object value) {
		boolean result = false;
		if (value != null) {
			result = true;
		}
		return result;
	}

	/**
	 * md5转换
	 * 
	 * @param data
	 * @return
	 */
	public static byte[] md5(byte[] data) {
		try {
			MessageDigest md = MessageDigest.getInstance("md5");
			md.update(data);
			return md.digest();
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		return new byte[] {};
	}

	// 运行时调用这个方法就行
	public static String md5(String data) {
		try {
			byte[] md5 = md5(data.getBytes("utf-8"));
			return toHexString(md5);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return "";
	}

	private static String toHexString(byte[] md5) {
		StringBuilder buf = new StringBuilder();
		for (byte b : md5) {
			buf.append(leftPad(Integer.toHexString(b & 0xff), '0', 2));
		}
		return buf.toString();
	}

	private static String leftPad(String hexString, char c, int size) {
		char[] cs = new char[size];
		Arrays.fill(cs, c);
		System.arraycopy(hexString.toCharArray(), 0, cs, cs.length
				- hexString.length(), hexString.length());
		return new String(cs);
	}

	// md5结束
	/**
	 * 向客户端写字符
	 * 
	 * @Title: doResponse
	 */
	public static void doResponse(HttpServletResponse response, String altMsg) {
		try {
			response.setContentType("text/html;charset=gbk");
			response.getWriter().write(altMsg);
			response.getWriter().flush();
			response.getWriter().close();
		} catch (IOException e) {
			System.out.println(e.getMessage());
		}
	}

	/**
	 * 删除某个文件夹下的所有文件夹和文件
	 * 
	 * @param delpath
	 *            String
	 * @throws FileNotFoundException
	 * @throws IOException
	 * @return boolean
	 */
	public static boolean deletefile(String delpath)
			throws FileNotFoundException, IOException {
		try {

			File file = new File(delpath);
			if (!file.isDirectory()) {
				System.out.println("1");
				file.delete();
			} else if (file.isDirectory()) {
				System.out.println("2");
				String[] filelist = file.list();
				for (int i = 0; i < filelist.length; i++) {
					File delfile = new File(delpath + "" + filelist[i]);
					if (!delfile.isDirectory()) {
						System.out.println("path=" + delfile.getPath());
						System.out.println("absolutepath="
								+ delfile.getAbsolutePath());
						System.out.println("name=" + delfile.getName());
						delfile.delete();
						System.out.println("删除文件成功");
					} else if (delfile.isDirectory()) {
						deletefile(delpath + "" + filelist[i]);
					}
				}
				file.delete();

			}

		} catch (FileNotFoundException e) {
			System.out.println("deletefile() Exception:" + e.getMessage());
		}
		return true;
	}

	/**
	 * 计算程序开始跑的时间，然后相减
	 * 
	 * @param args
	 */
	public static long starttime() {
		return System.currentTimeMillis();
	}

	/**
	 * 2013年08月07日 星期三 当前时间
	 * 
	 * @return
	 */
	public static String getDate() {

		Date now = new Date();
		SimpleDateFormat sf = new SimpleDateFormat("yyyy年MM月dd日 ");
		Calendar cal = Calendar.getInstance();
		int WeekOfYear = cal.get(Calendar.DAY_OF_WEEK);
		StringBuffer str = new StringBuffer();
		str.append(sf.format(now));
		String[] strs = { "日", "一", "二", "三", "四", "五", "六" };
		str.append("星期" + strs[WeekOfYear - 1]);
		return str.toString();
	}

	/**
	 * 只得到月，日
	 * 
	 * @return
	 */
	public static String getMonthAndDay() {

		Date now = new Date();
		SimpleDateFormat sf = new SimpleDateFormat("MM月dd日HH:mm ");
		StringBuffer str = new StringBuffer();
		str.append(sf.format(now));
		return str.toString();
	}

	/**
	 * 得到时间8位的
	 */

	public static String getnowday() {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
		String date = sdf.format(new Date()); // 把时间加入
		return date;
	}

	/**
	 * 数据库clob →string
	 * 
	 * @param args
	 */
	public static String ClobToString(Clob info) {
		String s1 = "";
		char ac[] = new char[200];
		if (info != null) {
			try {
				Reader reader = info.getCharacterStream();
				int j;
				while ((j = reader.read(ac, 0, 200)) != -1)
					s1 = s1 + new String(ac, 0, j);
				reader.close();
			} catch (Exception e) {
			}
		}
		return s1;
	}

	// 产生随机数
	/*
	 * randomStr()：生成随机字符串 String source：源字符串 int length：生成字符串长度
	 * 例如：source=0123456789 length=6
	 */
	public static String randomStr(String source, int length) {
		StringBuffer generateRandStr = new StringBuffer();
		Random rand = new Random();
		for (int i = 0; i < length; i++) {
			int randNum = rand.nextInt(source.length());
			generateRandStr.append(source.substring(randNum, randNum + 1));
		}
		return generateRandStr.toString();
	}

	/*
	 * 解析返回了的xml，存储HashMap形式
	 */
//	public static HashMap<String, Object> getxmltoHashmap(String requestParam) {
//		// System.out.println("requestParam："+requestParam);
//		HashMap<String, Object> hash = new HashMap<String, Object>();// 以键值对的形式存放参数
//		List list = new ArrayList();
//		String responxeXml = requestParam.replace("&", "&amp;");
//		// String responxeXml = requestParam;
//		// System.out.println("responxeXml："+responxeXml);
//		StringReader stringReader = new StringReader(responxeXml);
//		SAXReader saxReader = new SAXReader();
//		Document document;
//		try {
//			document = saxReader.read(stringReader);
//			Element root = document.getRootElement();
//
//			List<Element> childList = root.elements();
//			// System.out.println("--childList.size()--"+childList.size());
//			for (int i = 0; i < childList.size(); i++) {
//
//				if (childList.get(i).getName().equals("recordSet")) {
//
//					// for (Element e : (List<Element>)
//					// childList.get(i).elements()) {
//					// HashMap<String, String> hash1 = new HashMap<String,
//					// String>();// 以键值对的形式存放参数
//					//
//					// for (Element e2 : (List<Element>) e.elements()) {
//					// hash1.put(e2.getName(), e2.getText());//
//					// 解析XML后的值放到hashMap中
//					// }
//					// list.add(hash1);
//					//
//					// }
//					// hash.put("recordSet", list); //都没用
//				} else {
//					Element it = (Element) childList.get(i);
//					hash.put(it.getName(), it.getText());// 解析XML后的值放到hashMap中
//				}
//
//			}
//
//		} catch (Exception e) {
//
//		}
//		return hash;
//	}

	/**
	 * 获取1到10的随机奖励
	 * 
	 * @return
	 */
	public static int randomNumOne2Ten() {
		int res = (int) (long) (Math.random() * 11);
		if (res == 0) {
			res = 1;
		}
		return res;
	}

	// 这个jdk版本问题
	/**
	 * 读取excel文件
	 */
	// public static List<String> readExcel(String filePath) {
	// Workbook wb = null;
	// List<String> list = new ArrayList<String>();
	// try {
	//
	// wb = Workbook.getWorkbook(new File(filePath));
	// Sheet sheet = wb.getSheet(0);
	// int row = sheet.getRows();
	// int col = sheet.getColumns();
	// for (int i = 0; i < row; i++) {
	// Cell[] cell = sheet.getRow(i);
	// String content = "";
	// for (int j = 0; j < cell.length; j++) {
	// if (GuWeiUtil.isNotEmpty(cell[j].getContents())) {
	// if (j == 0) {
	// content += cell[j].getContents();
	// } else {
	// content += "@@" + cell[j].getContents();
	// }
	// } else {
	// break;
	// }
	// }
	// if (GuWeiUtil.isNotEmpty(content))
	// list.add(content);
	// }
	// list.remove(0);
	// } catch (BiffException e) {
	// // TODO Auto-generated catch block
	// e.printStackTrace();
	// } catch (IOException e) {
	//			 
	// }
	// return list;
	// }

	/**
	 * 测试是否为邮件
	 */
	public static boolean isEmail(String email) {
		String str = "^([a-zA-Z0-9]*[-_]?[a-zA-Z0-9]+)*@([a-zA-Z0-9]*[-_]?[a-zA-Z0-9]+)+[\\.][A-Za-z]{2,3}([\\.][A-Za-z]{2})?$";
		Pattern p = Pattern.compile(str);
		Matcher m = p.matcher(email);
		return m.matches();
	}

	/**
	 * 生成随即数字 按年月日
	 * 
	 * @return
	 */
	public static String createId() {
		Date now = new Date();
		SimpleDateFormat sf = new SimpleDateFormat("yyyyMMddHHmmss");
		StringBuffer str = new StringBuffer();
		str.append(sf.format(now));
		str.append(genRandomNum(8));
		return str.toString();
	}

	/**
	 * 根据几位数生成随即数
	 * 
	 * @param pwd_len
	 * @return
	 */
	public static String genRandomNum(int pwd_len) {
		int count = 0;
		char str[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
		StringBuffer pwd = new StringBuffer("");
		Random r = new Random();
		while (count < pwd_len) {
			int i = Math.abs(r.nextInt(10));
			if (i >= 0 && i < str.length) {
				pwd.append(str[i]);
				count++;
			}
		}
		return pwd.toString();
	}

	// 生成随即数字结束

	/**
	 * ping端口通不通
	 */
	public static void ping(int a, int b, int c, int d) {

		try {
			int timeOut = 3000;
			byte[] ip = new byte[] { (byte) a, (byte) b, (byte) c, (byte) d };
			int retry = 1111;
			InetAddress address = InetAddress.getByAddress(ip);
			for (int i = 0; i < retry; i++) {
				if (address.isReachable(timeOut)) {
					System.out.println(i + " OK");
				} else {
					System.out.println(i + " LOSS");
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	// ----------各种编码互转------------

	public String gbk2utf8(String gbk) {
		String l_temp = GBK2Unicode(gbk);
		l_temp = unicodeToUtf8(l_temp);

		return l_temp;
	}

	public String utf82gbk(String utf) {
		String l_temp = utf8ToUnicode(utf);
		l_temp = Unicode2GBK(l_temp);

		return l_temp;
	}

	/**
	 * 
	 * @param str
	 * @return String
	 */

	public static String GBK2Unicode(String str) {
		StringBuffer result = new StringBuffer();
		for (int i = 0; i < str.length(); i++) {
			char chr1 = (char) str.charAt(i);

			if (!isNeedConvert(chr1)) {
				result.append(chr1);
				continue;
			}

			result.append("\\u" + Integer.toHexString((int) chr1));
		}

		return result.toString();
	}

	/**
	 * 
	 * @param dataStr
	 * @return String
	 */

	public static String Unicode2GBK(String dataStr) {
		int index = 0;
		StringBuffer buffer = new StringBuffer();

		int li_len = dataStr.length();
		while (index < li_len) {
			if (index >= li_len - 1
					|| !"\\u".equals(dataStr.substring(index, index + 2))) {
				buffer.append(dataStr.charAt(index));

				index++;
				continue;
			}

			String charStr = "";
			charStr = dataStr.substring(index + 2, index + 6);

			char letter = (char) Integer.parseInt(charStr, 16);

			buffer.append(letter);
			index += 6;
		}

		return buffer.toString();
	}

	public static boolean isNeedConvert(char para) {
		return ((para & (0x00FF)) != para);
	}

	/**
	 * utf-8 转unicode
	 * 
	 * @param inStr
	 * @return String
	 */
	public static String utf8ToUnicode(String inStr) {
		char[] myBuffer = inStr.toCharArray();

		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < inStr.length(); i++) {
			UnicodeBlock ub = UnicodeBlock.of(myBuffer[i]);
			if (ub == UnicodeBlock.BASIC_LATIN) {
				sb.append(myBuffer[i]);
			} else if (ub == UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS) {
				int j = (int) myBuffer[i] - 65248;
				sb.append((char) j);
			} else {
				short s = (short) myBuffer[i];
				String hexS = Integer.toHexString(s);
				String unicode = "\\u" + hexS;
				sb.append(unicode.toLowerCase());
			}
		}
		return sb.toString();
	}

	/**
	 * 
	 * @param theString
	 * @return String
	 */
	public static String unicodeToUtf8(String theString) {
		char aChar;
		int len = theString.length();
		StringBuffer outBuffer = new StringBuffer(len);
		for (int x = 0; x < len;) {
			aChar = theString.charAt(x++);
			if (aChar == '\\') {
				aChar = theString.charAt(x++);
				if (aChar == 'u') {
					// Read the xxxx
					int value = 0;
					for (int i = 0; i < 4; i++) {
						aChar = theString.charAt(x++);
						switch (aChar) {
						case '0':
						case '1':
						case '2':
						case '3':
						case '4':
						case '5':
						case '6':
						case '7':
						case '8':
						case '9':
							value = (value << 4) + aChar - '0';
							break;
						case 'a':
						case 'b':
						case 'c':
						case 'd':
						case 'e':
						case 'f':
							value = (value << 4) + 10 + aChar - 'a';
							break;
						case 'A':
						case 'B':
						case 'C':
						case 'D':
						case 'E':
						case 'F':
							value = (value << 4) + 10 + aChar - 'A';
							break;
						default:
							throw new IllegalArgumentException(
									"Malformed   \\uxxxx   encoding.");
						}
					}
					outBuffer.append((char) value);
				} else {
					if (aChar == 't')
						aChar = '\t';
					else if (aChar == 'r')
						aChar = '\r';
					else if (aChar == 'n')
						aChar = '\n';
					else if (aChar == 'f')
						aChar = '\f';
					outBuffer.append(aChar);
				}
			} else
				outBuffer.append(aChar);
		}
		return outBuffer.toString();
	}

	// ----------各种编码互转------------

	/**
	 * 传入文件计算其MD5校验码
	 * 
	 * @param file
	 * @return
	 */
	public String getFileMD5String(File file) {
		MessageDigest messagedigest = null;
		try {
			messagedigest = MessageDigest.getInstance("MD5");
		} catch (NoSuchAlgorithmException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		FileInputStream fis = null;
		try {
			fis = new FileInputStream(file);
			byte[] buffer = new byte[8192];
			int length = -1;
			while ((length = fis.read(buffer)) != -1) {
				messagedigest.update(buffer, 0, length);
			}
			return bufferToHex(messagedigest.digest()).toUpperCase();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (fis != null) {
					fis.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return "";
	}

	private String bufferToHex(byte bytes[]) {
		return bufferToHex(bytes, 0, bytes.length);
	}

	private String bufferToHex(byte bytes[], int m, int n) {
		StringBuffer stringbuffer = new StringBuffer(2 * n);
		int k = m + n;
		for (int l = m; l < k; l++) {
			appendHexPair(bytes[l], stringbuffer);
		}
		return stringbuffer.toString();
	}

	private void appendHexPair(byte bt, StringBuffer stringbuffer) {
		char c0 = hexDigits[(bt & 0xf0) >> 4];
		char c1 = hexDigits[bt & 0xf];
		stringbuffer.append(c0);
		stringbuffer.append(c1);
	}

	protected static char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6',
			'7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };

	/**
	 * 用流拷贝文件
	 * 
	 */
	public static void copyFile(File file, File file1) {

		FileInputStream fread;
		BufferedInputStream reader = null;
		BufferedOutputStream write = null;
		try {
			fread = new FileInputStream(file);
			reader = new BufferedInputStream(fread);
			write = new BufferedOutputStream(new FileOutputStream(file1));
			byte b[] = new byte[1024];
			int i = -1;
			while ((i = reader.read(b)) != -1) {

				write.write(b, 0, i); // 写入
				// write.write(b); //写入 错误
				write.flush();
				// System.out.println(b);
			}
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				reader.close();
				write.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

	}

	/**
	 * 控制流量传输
	 */
//	public void controlTransfer() {
//		File file = new File("D:/123/gshou.txt");
//		FileInputStream filein;
//		try {
//			filein = new FileInputStream(file);
//			BufferedInputStream in = new BufferedInputStream(filein);
//			FlowController f = new FlowController(in);
//		} catch (FileNotFoundException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
//
//	}

	/**
	 * 用流拷贝文件 ,规定指定字节
	 * 
	 */
	public static void copyFileByLength() {

		File file = new File("D:/123/1.jpg");
		FileInputStream fread;
		BufferedInputStream reader = null;
		BufferedOutputStream write = null;
		try {
			fread = new FileInputStream(file);
			reader = new BufferedInputStream(fread);

			write = new BufferedOutputStream(new FileOutputStream(new File(
					"D:/123/g1.jpg")));
			byte b[] = new byte[1024];
			int i = -1;
			int allb = 4000;
			while ((i = reader.read(b)) != -1) {
				if (allb < 1024) {
					i = allb;
					write.write(b, 0, i); // 跳出循环
					break;
				}
				write.write(b, 0, i); // 写入
				// write.write(b); //写入 错误
				write.flush();
				allb = allb - i; // i是已读的字节数
			}
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				reader.close();
				write.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

	}

	/**
	 * 跌代
	 */
	public void removeList() {

		List list = new ArrayList();
		Iterator iterator = list.iterator();

		while (iterator.hasNext()) {
			Object a = iterator.next();
			// 条件
			if (1 == 1) {
				iterator.remove();
			}
		}
	}

	private boolean send_url(String urlStr) {
		String param = "";
		int count = 0; // 计算得到的图片流的大小
		HttpURLConnection url_con = null;
		try {
			URL url = new URL(urlStr);
			url_con = (HttpURLConnection) url.openConnection();
			url_con.setRequestMethod("POST");
			url_con.setDoOutput(true);

			url_con.getOutputStream().write(param.getBytes());
			url_con.getOutputStream().flush();
			url_con.getOutputStream().close();
			InputStream inPut = url_con.getInputStream();
			BufferedInputStream in = new BufferedInputStream(inPut);
			// BufferedReader rd = new BufferedReader(new
			// InputStreamReader(in));
			// while (rd.read() != -1) {
			// tempStr.append(rd.readLine());
			// }
			if (in != null) {
				byte[] b = new byte[1024];
				int len = 0;
				while ((len = in.read(b)) != -1) {
					// 写入输出流
					count += len;
				}
			}
		} catch (Exception e) {

			return false;
		} finally {
			if (url_con != null)
				url_con.disconnect();

		}

		if (count > 0) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * 得到url并解析文件是否存在
	 * 
	 * @param responxeXml
	 * @throws Exception
	 */
//	public boolean getEliemt(String responxeXml, int count) {
//		// SAXReader reader = new SAXReader();
//		// Document document = reader.read(new File("D://5batchid.xml"));
//
//		StringReader stringReader = new StringReader(responxeXml);
//		SAXReader saxReader = new SAXReader();
//		try {
//			Document document = saxReader.read(stringReader);
//			Element root = document.getRootElement(); // 获取根节点
//			Element batch = root.element("BATCH"); // 得到batch节点
//			Element images = batch.element("IMAGES"); // IMAGES节点
//			if (images == null) {
//
//				return false;
//			}
//			List imagesList = images.elements(); // image节点的list
//			if (imagesList.size() != count) {
//
//				return false;
//			}
//			// 解析IMAGE节点
//			for (Iterator iterator = images.elementIterator("IMAGE"); iterator
//					.hasNext();) {
//				Element imag = (Element) iterator.next();
//				String url = imag.attributeValue("URL");
//
//				if (!send_url(url)) {
//
//					return false;
//				}
//			}
//
//		} catch (DocumentException e) {
//			return false;
//		}
//		return true;
//
//	}

	public static boolean isBlank(String args) {
		if (null == args || "".endsWith(args.replace(" ", ""))) {
			return true;
		}
		return false;
	}

	/**
	 * 根据提供的节点名称,从XML文件中读取相应的值
	 * 
	 * @param String
	 *            node 节点名称
	 * @return Map<String, String> 返回节点值
	 * */
	@SuppressWarnings("unchecked")
	// public static Map<String, String> getXml(String xpath) {
	// if (GuWeiUtil.isBlank(xpath)) {
	// return null;
	// }
	// InputStream is = null;
	// Map<String, String> map = new HashMap<String, String>();
	// SAXReader sax = new SAXReader();
	// Document doc = null;
	// try {
	// try {
	// is = GuWeiUtil.class.getClassLoader().getResourceAsStream(
	// "config-morit.xml");
	// doc = sax.read(is);
	// List<Element> list = doc.selectNodes(xpath);
	// if (null == list || 0 >= list.size()) {
	// return null;
	// }
	// for (Element e : list) {
	// if (null == e || GuWeiUtil.isBlank(e.getName())) {
	// continue;
	// }
	// map.put(e.getName(), e.getText());
	// }
	// } finally {
	// if (is != null)
	// is.close();
	// }
	// } catch (DocumentException e) {
	// e.printStackTrace();
	// } catch (IOException e1) {
	// e1.printStackTrace();
	// }
	// return map;
	// }

	/**
	 * 保留指定位数的小数(最后一位四舍五入)
	 * 
	 * @param Float
	 *            f 待处理数
	 * @param int n 保留小数位数
	 * @return float
	 * */
	public static float mathRound(float f, int n) {
		if (-1 >= n) {
			return f;
		}
		String xs = "#0";
		for (int i = 0; i < n; i++) {
			if (0 == i) {
				xs += ".";
			}
			xs += "0";
		}
		DecimalFormat df = new DecimalFormat(xs);
		float result = Float.valueOf(df.format(f));
		return result;
	}

	/**
	 * SNMP传输协议中把十六进制转换成中文
	 * 
	 * @param String
	 *            input 十六进制字符串
	 * @return String 返回转换后的字符串
	 * */
	public String exchange(String input) {
		String result;
		StringBuffer sb = new StringBuffer();
		String hexs = input;
		String[] sa = hexs.split(":");
		for (String s : sa) {
			char c = (char) (Integer.parseInt(s, 16));
			sb.append(c);
		}
		result = sb.toString();
		try {
			result = new String(result.getBytes("ISO-8859-1"), "gb2312");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return result;
	}

	/**
	 * 校验spring是否实例化
	 */
	public void Spring() {
		// ApplicationContext ctx = new
		// ClassPathXmlApplicationContext("file:C:/Documents and Settings/Administrator/Workspaces/MyEclipse 8.6/SunECMConsole3.41/WebRoot/WEB-INF/applicationContext.xml");
		// LogRuleManageAction students =
		// (LogRuleManageAction)ctx.getBean("logRuleManageAction");
		// System.out.println(students);
		// 引入的类
		// import org.springframework.context.ApplicationContext;
		// import
		// org.springframework.context.support.ClassPathXmlApplicationContext;
		//
		// import com.sunyard.console.logmanage.action.LogRuleManageAction;
	}

	public void getNeiCun() {
		Runtime run = Runtime.getRuntime();

		long max = run.maxMemory();

		long total = run.totalMemory();

		long free = run.freeMemory();

		long usable = max - total + free;
	}

	/**
	 * 转成网页 的
	 * 
	 * @param target
	 * @return
	 */
	public static String htmEncode(String target) {
		StringBuffer stringbuffer = new StringBuffer();
		int j = target.length();
		for (int i = 0; i < j; i++) {
			char c = target.charAt(i);
			switch (c) {
			case 60:
				stringbuffer.append("&lt;");
				break;
			case 62:
				stringbuffer.append("&gt;");
				break;
			case 38:
				stringbuffer.append("&amp;");
				break;
			case 34:
				stringbuffer.append("&quot;");
				break;
			case 169:
				stringbuffer.append("&copy;");
				break;
			case 174:
				stringbuffer.append("&reg;");
				break;
			case 165:
				stringbuffer.append("&yen;");
				break;
			case 8364:
				stringbuffer.append("&euro;");
				break;
			case 8482:
				stringbuffer.append("&#153;");
				break;
			case 13:
				stringbuffer.append("<br>");
				break;
			case 32:
				stringbuffer.append("&nbsp;");
				break;
			default:
				stringbuffer.append(c);
				break;
			}
		}
		return new String(stringbuffer.toString());
	}

	/**
	 * 得到文件类型
	 * 
	 * @param extName
	 * @return
	 */
	public static String getMiniType(String extName) {
		extName = extName.toLowerCase();
		if (extName.equals("tif")) {
			return "image/tiff";
		} else if (extName.equals("tiff")) {
			return "image/tiff";
		} else if (extName.equals("bmp")) {
			return "image/bmp";
		} else if (extName.equals("gif")) {
			return "image/gif";
		} else if (extName.equals("jpg")) {
			return "image/jpeg";
		} else if (extName.equals("jpe")) {
			return "image/jpeg";
		} else if (extName.equals("jpeg")) {
			return "image/jpeg";
		} else if (extName.equals("doc") || extName.equals("docx")) {
			return "application/msword";
		} else if (extName.equals("dot")) {
			return "application/msword";
		} else if (extName.equals("rtf")) {
			return "application/msword";
		} else if (extName.equals("xls")) {
			return "application/vnd.ms-excel";
		} else if (extName.equals("ppt")) {
			return "application/vnd.ms-powerpoint";
		} else if (extName.equals("vsd")) {
			return "application/vnd.visio";
		} else if (extName.equals("wp")) {
			return "application/wordperfect5.1";
		} else if (extName.equals("txt")) {
			return "text/plain";
		} else if (extName.equals("html")) {
			return "text/html";
		} else if (extName.equals("htm")) {
			return "text/html";
		} else if (extName.equals("txt")) {
			return "text/plain";
		} else if (extName.equals("java")) {
			return "text/plain";
		} else if (extName.equals("body")) {
			return "text/html";
		} else if (extName.equals("rtx")) {
			return "text/richtext";
		} else if (extName.equals("tsv")) {
			return "text/tab-separated-values";
		} else if (extName.equals("etx")) {
			return "text/x-setext";
		} else if (extName.equals("ps")) {
			return "application/x-postscript";
		} else if (extName.equals("class")) {
			return "application/java";
		} else if (extName.equals("csh")) {
			return "application/x-csh";
		} else if (extName.equals("sh")) {
			return "application/x-sh";
		} else if (extName.equals("tcl")) {
			return "application/x-tcl";
		} else if (extName.equals("tex")) {
			return "application/x-tex";
		} else if (extName.equals("texinfo")) {
			return "application/x-texinfo";
		} else if (extName.equals("texi")) {
			return "application/x-texinfo";
		} else if (extName.equals("t")) {
			return "application/x-troff";
		} else if (extName.equals("tr")) {
			return "application/x-troff";
		} else if (extName.equals("roff")) {
			return "application/x-troff";
		} else if (extName.equals("man")) {
			return "application/x-troff-man";
		} else if (extName.equals("me")) {
			return "application/x-troff-me";
		} else if (extName.equals("ms")) {
			return "application/x-wais-source";
		} else if (extName.equals("src")) {
			return "application/x-wais-source";
		} else if (extName.equals("zip")) {
			return "application/zip";
		} else if (extName.equals("bcpio")) {
			return "application/x-bcpio";
		} else if (extName.equals("cpio")) {
			return "application/x-cpio";
		} else if (extName.equals("gtar")) {
			return "application/x-gtar";
		} else if (extName.equals("shar")) {
			return "application/x-shar";
		} else if (extName.equals("sv4cpio")) {
			return "application/x-sv4cpio";
		} else if (extName.equals("sv4crc")) {
			return "application/x-sv4crc";
		} else if (extName.equals("tar")) {
			return "application/x-tar";
		} else if (extName.equals("ustar")) {
			return "application/x-ustar";
		} else if (extName.equals("dvi")) {
			return "application/x-dvi";
		} else if (extName.equals("hdf")) {
			return "application/x-hdf";
		} else if (extName.equals("latex")) {
			return "application/x-latex";
		} else if (extName.equals("bin")) {
			return "application/octet-stream";
		} else if (extName.equals("oda")) {
			return "application/oda";
		} else if (extName.equals("pdf")) {
			return "application/pdf";
		} else if (extName.equals("ps")) {
			return "application/postscript";
		} else if (extName.equals("eps")) {
			return "application/postscript";
		} else if (extName.equals("ai")) {
			return "application/postscript";
		} else if (extName.equals("rtf")) {
			return "application/rtf";
		} else if (extName.equals("nc")) {
			return "application/x-netcdf";
		} else if (extName.equals("cdf")) {
			return "application/x-netcdf";
		} else if (extName.equals("cer")) {
			return "application/x-x509-ca-cert";
		} else if (extName.equals("exe")) {
			return "application/octet-stream";
		} else if (extName.equals("gz")) {
			return "application/x-gzip";
		} else if (extName.equals("Z")) {
			return "application/x-compress";
		} else if (extName.equals("z")) {
			return "application/x-compress";
		} else if (extName.equals("hqx")) {
			return "application/mac-binhex40";
		} else if (extName.equals("mif")) {
			return "application/x-mif";
		} else if (extName.equals("ief")) {
			return "image/ief";
		} else if (extName.equals("ras")) {
			return "image/x-cmu-raster";
		} else if (extName.equals("pnm")) {
			return "image/x-portable-anymap";
		} else if (extName.equals("pbm")) {
			return "image/x-portable-bitmap";
		} else if (extName.equals("pgm")) {
			return "image/x-portable-graymap";
		} else if (extName.equals("ppm")) {
			return "image/x-portable-pixmap";
		} else if (extName.equals("rgb")) {
			return "image/x-rgb";
		} else if (extName.equals("xbm")) {
			return "image/x-xbitmap";
		} else if (extName.equals("xpm")) {
			return "image/x-xpixmap";
		} else if (extName.equals("xwd")) {
			return "image/x-xwindowdump";
		} else if (extName.equals("au")) {
			return "audio/basic";
		} else if (extName.equals("snd")) {
			return "audio/basic";
		} else if (extName.equals("aif")) {
			return "audio/x-aiff";
		} else if (extName.equals("aiff")) {
			return "audio/x-aiff";
		} else if (extName.equals("aifc")) {
			return "audio/x-aiff";
		} else if (extName.equals("wav")) {
			return "audio/x-wav";
		} else if (extName.equals("mpeg")) {
			return "video/mpeg";
		} else if (extName.equals("mpg")) {
			return "video/mpeg";
		} else if (extName.equals("mpe")) {
			return "video/mpeg";
		} else if (extName.equals("qt")) {
			return "video/quicktime";
		} else if (extName.equals("mov")) {
			return "video/quicktime";
		} else if (extName.equals("avi")) {
			return "video/x-msvideo";
		} else if (extName.equals("movie")) {
			return "video/x-sgi-movie";
		} else if (extName.equals("avx")) {
			return "video/x-rad-screenplay";
		} else if (extName.equals("wrl")) {
			return "x-world/x-vrml";
		} else if (extName.equals("mpv2")) {
			return "video/mpeg2";
		} else {
			return "application/octet-stream";
		}
	}

 
	/**
	 * 根据地址能生成文件夹默认在D盘
	 */
	public static void produceFile(String path) {
		// path = "com.sunyard.dmserver.batchmigrate.thread.ContentMigrate";
		String[] pathList = path.split("[.]");
		StringBuffer myPath = new StringBuffer("D:/TEST/");
		String className = "";
		for (int i = 0; i < pathList.length; i++) {
			if (i < pathList.length - 1) {
				myPath.append(pathList[i]).append("/"); // 文件夹的名字
			} else {
				className = (pathList[i]); // 文件的名字
			}
		}
		String foliderPath = myPath.toString();
		// System.out.println(foliderPath);
		File outfile = new File(foliderPath);

		if (!outfile.isFile()) {
			outfile.mkdirs(); // 创建文件夹
		}

		String allClassFile = "D:/TEST/"; // 文件都在D盘的tst下

		File file = new File(allClassFile + className + ".class"); // 实际文件地址
		File file1 = new File(foliderPath + className + ".class"); // 复制的文件地址
		copyFile(file, file1);

		file.delete();
	}

	/*
	 * 根据test文件得到每个类名
	 */
	public static void produceAllFile(String testPath) {

		try {
			FileReader read;
			read = new FileReader(testPath);
			BufferedReader br = new BufferedReader(read);
			String row;
			StringBuffer str = new StringBuffer("");

			while ((row = br.readLine()) != null) {
				// list.add(row);
				str.append(row + ",");
			}
			String strs = str.toString();
			String[] eachPath = strs.split(",");
			for (String path : eachPath) {
				produceFile(path); // 执行每个
			}

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	/**
	 * 测试方法
	 */
	// public static void main(String[] args) {
	// // File file=new File("D://123//test//a.jpg");
	//		
	//		
	// // for (int i = 0; i < 2000; i++) {
	// // File file1=new File("D://123//test//"+i+".jpg");
	// // System.out.println(i);
	// // copyFile(file, file1);
	// // }
	//		
	// produceAllFile("D:/TEST/类的地址.txt");
	//		
	// // System.out.println(gethostIPaddress());;
	//		 
	//		 
	//		
	// }

	public static void fileChannelCopy(File s, File t) {

		FileInputStream fi = null;

		FileOutputStream fo = null;

		FileChannel in = null;

		FileChannel out = null;

		try {

			fi = new FileInputStream(s);

			fo = new FileOutputStream(t);

			in = fi.getChannel();// 得到对应的文件通道

			out = fo.getChannel();// 得到对应的文件通道
			System.out.println("out.size()"+out.size());
			in.transferTo(0, in.size(), out);// 连接两个通道，并且从in通道读取，然后写入out通道

		} catch (IOException e) {

			e.printStackTrace();

		} finally {

			try {

				fi.close();

				in.close();

				fo.close();

				out.close();

			} catch (IOException e) {

				e.printStackTrace();

			}

		}

	}

	/**
	 * 追加文件
	 * @param fileName
	 * @param content
	 */
	 public static void appendMethodA(String fileName, String content) {
	        try {
	            // 打开一个随机访问文件流，按读写方式

	            RandomAccessFile randomFile = new RandomAccessFile(fileName, "rw");
	            // 文件长度，字节数

	            long fileLength = randomFile.length();
	            //将写文件指针移到文件尾。

	            randomFile.seek(fileLength);
	            randomFile.writeBytes(content);
	            
	            randomFile.close();
	        } catch (IOException e) {
	            e.printStackTrace();
	        }
	    }

	
 
	
	/**
	 * 16进制转成10进制
	 */
	public static void OneSixTo10(String a) {
		System.out.println(Integer.parseInt(a, 16));
	}

	public static void TenTO16(int c) {
		String a = Integer.toHexString(c).toUpperCase();
		System.out.println(a);
	}

	public static void main(String[] args) {
		appendMethodA("D://123//1.jpg", "D://123//2.jpg");
		
		
		
	}
}
